package com.ruoyi.common.utils.sign;

import com.alibaba.fastjson2.JSONObject;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public final class DecryptData {
    public static JSONObject decryptData(String sessionKey, String encryptedData, String iv) throws Exception {
        // 对密钥进行 Base64 解码
        byte[] keyBytes = Base64.getDecoder().decode(sessionKey);
        byte[] encryptedDataBytes = Base64.getDecoder().decode(encryptedData);
        byte[] ivBytes = Base64.getDecoder().decode(iv);

        // 使用 AES 解密算法进行解密
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] decryptedBytes = cipher.doFinal(encryptedDataBytes);
        JSONObject json = JSONObject.parseObject(new String(decryptedBytes, "UTF-8"));
        return json;
    }
}
